package com.itheima.controller.backend;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.OrderSettingResult;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.StringJoiner;

@RestController
@Slf4j
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 预约设置
     *
     * @return
     */
    @PostMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSetting orderSetting) {

        orderSettingService.editNumberByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }

    /**
     * 获取预约设置数据
     *
     * @param monthStr
     * @return
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam("month") String monthStr) {

        log.info("获取预约设置数据：{}", monthStr);

        StringJoiner sj = new StringJoiner("-");
        int last = monthStr.lastIndexOf("-");
        String year = monthStr.substring(0, last);
        String month = monthStr.substring(last + 1);
        log.info("获取年：{}", year);
        log.info("获取月：{}", month);
        if (month.length() == 1) {
            month = "0" + month;
            sj.add(year).add(month);
            log.info("拼接年月：{}", sj);
            List<OrderSettingResult> list = orderSettingService.getOrderSettingByMonth(sj.toString());
            return new Result(true, "获取预约设置数据成功", list);
        }
        List<OrderSettingResult> list = orderSettingService.getOrderSettingByMonth(month);
        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);

    }

    /**
     * 文件上传
     * @return
     */
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile excelFile) throws Exception {

        if(excelFile == null){
            return new Result(false, "文件为空");
        }
        log.info("文件上传：{}", excelFile);
        orderSettingService.upload(excelFile);
        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    /**
     * 文件下载
     * @return
     */
    @GetMapping("/download")
    public String download(@RequestParam("fileName") String fileName){
        log.info("文件下载：{}", fileName);
        orderSettingService.download(fileName);
        return "文件下载";
    }

}
